import datetime
import os

import face_recognition
from flask import Flask, request, send_from_directory

app = Flask(__name__)

# 确保上传目录存在
TARGET_FOLDER = 'D:/faceid/target'
DATA_FOLDER = 'D:/faceid/picDb'
if not os.path.exists(TARGET_FOLDER):
    os.makedirs(TARGET_FOLDER)
if not os.path.exists(DATA_FOLDER):
    os.makedirs(DATA_FOLDER)


# 图库数据上传
@app.route('/upPicDb', methods=['POST'])
def upPicDb():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    # 检查文件是否有文件名
    if file.filename == '':
        return 'No selected file', 400
    if file:
        # 拼接文件保存路径
        file_path = os.path.join(DATA_FOLDER, file.filename)
        try:
            file.save(file_path)
            return 'File uploaded successfully', 200
        except Exception as e:
            return f'Error uploading file: {str(e)}', 500


# 加载已知人脸照片库
known_face_encodings = []
known_face_names = []


# 样本上传 对比
@app.route('/checkPic', methods=['POST'])
def checkPic():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    # 检查文件是否有文件名
    if file.filename == '':
        return 'No selected file', 400
    if file:
        # 拼接文件保存路径
        file_path = os.path.join(TARGET_FOLDER, file.filename)
        try:
            file.save(file_path)
            for filename in os.listdir(DATA_FOLDER):
                if filename.endswith(('.png', '.jpg', '.jpeg')):
                    image = face_recognition.load_image_file(os.path.join(DATA_FOLDER, filename))
                    face_encoding = face_recognition.face_encodings(image)
                    if face_encoding:
                        known_face_encodings.append(face_encoding[0])
                        known_face_names.append(os.path.splitext(filename)[0])
            # 加载新照片
            unknown_image = face_recognition.load_image_file(file_path)
            # 查找新照片中所有人脸的位置和特征编码
            face_locations = face_recognition.face_locations(unknown_image)
            face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
            tmp = -0.1
            similarity1 = -0.1
            top1 = -0.1
            right1 = -0.1
            bottom1 = -0.1
            left1 = -0.1
            name1 = ""
            for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
                # 计算与已知人脸的距离（距离越小，匹配度越高）
                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = face_distances.argmin()
                name = known_face_names[best_match_index]
                similarity = (1 - face_distances[best_match_index]) * 100  # 将距离转换为匹配度百分比
                if similarity > tmp:
                    tmp = similarity
                    top1 = top
                    right1 = right
                    bottom1 = bottom
                    left1 = left
                    name1 = name
                    similarity1 = similarity
                retn = {
                    "top1": top1,
                    "right1": right1,
                    "bottom1": bottom1,
                    "left1": left1,
                    "name1": name1,
                    "similarity1": f"{similarity1:.2f}%",
                }
            return retn
        except Exception as e:
            return f'Error uploading file: {str(e)}', 500


@app.route('/b')
def rewritten_view():
    return "str(i)"


UPLOAD_FOLDER = 'D:/upload'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    # 检查文件是否有文件名
    if file.filename == '':
        return 'No selected file', 400
    if file:
        # 拼接文件保存路径
        file_path = os.path.join(UPLOAD_FOLDER, file.filename)
        try:
            # 保存文件
            file.save(file_path)
            return 'File uploaded successfully', 200
        except Exception as e:
            return f'Error uploading file: {str(e)}', 500


@app.route('/download/<path:filename>', methods=['GET'])
def download_file(filename):
    try:
        # 从指定目录发送文件
        return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)
    except FileNotFoundError:
        return 'File not found', 404


@app.route('/a')
def original_view():
    curtime = datetime.datetime.now()
    datestr = curtime.strftime("%Y-%m-%d %H:%M:%S")
    return datestr


if __name__ == '__main__':
    app.run(debug=True, port=8899)
